package com.goldze.mvvmhabit.ui.vp_frg;

import android.app.Application;
import android.support.annotation.NonNull;

import com.goldze.mvvmhabit.data.DemoRepository;
import com.goldze.mvvmhabit.entity.response.GetNewMsgResponseEntity;

import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.utils.RxUtils;

public class ViewPagerGroupViewModel extends BaseViewModel<DemoRepository> {

    public SingleLiveEvent<Integer> newMsg = new SingleLiveEvent<>();

    public ViewPagerGroupViewModel(@NonNull Application application, DemoRepository repository) {
        super(application, repository);
    }

    public void getNewMsg() {
        model.getNewMsg()
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                    }
                })
                .subscribe(new Consumer<BaseResponse<List<GetNewMsgResponseEntity>>>() {
                    @Override
                    public void accept(BaseResponse<List<GetNewMsgResponseEntity>> response) throws Exception {
                        if (response.getResponse() == null) {
                            newMsg.setValue(0);
                            return;
                        }
                        int count = 0;
                        for (GetNewMsgResponseEntity mGetNewMsgResponseEntity : response.getResponse()) {
                            if (!mGetNewMsgResponseEntity.isIsread()) {
                                count++;
                            }
                        }
                        newMsg.setValue(count);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                    }
                });
    }

}
